﻿using System.Windows.Forms;
using SharePointUtilitiesForDevelopers.Action;
using SharePointUtilitiesForDevelopers.Repository;

namespace SharePointUtilitiesForDevelopers.Actions
{
    /// <summary>
    /// A custom action for getting list items.
    /// </summary>
    public class GetListItemsAction: IAction
    {
        private readonly ISharePointListRepository _listRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="GetListItemsAction"/> class.
        /// </summary>
        /// <param name="listRepository">The list repository.</param>
        public GetListItemsAction(ISharePointListRepository listRepository)
        {
            _listRepository = listRepository;
        }

        /// <summary>
        /// Gets the title.
        /// </summary>
        /// <value>The title.</value>
        public string Title
        {
            get { return Properties.Resources.GetListItemsActionTitle; }
        }

        /// <summary>
        /// Gets the description.
        /// </summary>
        /// <value>The description.</value>
        public string Description
        {
            get { return Properties.Resources.GetListItemsActionDescription; }
        }

        /// <summary>
        /// Gets the target.
        /// </summary>
        /// <value>The target.</value>
        public ActionTarget Target
        {
            get { return ActionTarget.List | ActionTarget.ListView; }
        }

        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="actionContext">The context.</param>
        public void Execute(ActionContext actionContext)
        {
            var form = ServiceLocator.Resolve<ListItemsForm>();
            form.Web = actionContext.Web;

            if (actionContext.Entity is SharePointList)
            {
                form.List = (SharePointList)actionContext.Entity;
            }

            if (actionContext.Entity is SharePointListView)
            {
                form.View = (SharePointListView)actionContext.Entity;
                form.List = _listRepository.GetList(actionContext.Web.Url, form.View.ListName, new SharePointListLoadOptions());
            }

            form.ShowDialog(actionContext.Owner as IWin32Window);
        }
    }
}